/*
 * W3C Markup Validation with JavaScript
 * Copyright (c) 2008 Jacob Seidelin, cupboy@gmail.com, http://blog.nihilogic.dk/
 * MIT License [http://www.opensource.org/licenses/mit-license.php]
 */

/*

This file provides a function for validating a page against the W3C validator. 
It uses Simon Willison's json-head micro-service to send HEAD requests.

function validate(url, callback, [error]) { ... }

where callback is a function that takes one argument which is a response object with the properties:
{
	url : [string]
	status : [string]
	errors : [integer]
	warnings : [integer]
	recursion : [integer]
}

the optional "error" argument is a function that will be called if the validation request is not succesful. 
This function also takes a response object that has the "url" property as well as a "head" property with the response from json-head.

See http://validator.w3.org/docs/api.html#http_headers for details on what each of these properties/headers mean.

*/

var validate = (function() {

	window.__validate_callbacks = {};
	var callCount = 0;

	return function(url, callback, error) {
		callCount++;

		var script = document.createElement("script");

		window.__validate_callbacks["fn_" + callCount] = function(head) {
			document.body.removeChild(script);
			if (head.status_code == 200) {
				var response = {
					url : url,
					status : head.headers["X-W3C-Validator-Status"],
					errors : parseInt(head.headers["X-W3C-Validator-Errors"],10),
					warnings : parseInt(head.headers["X-W3C-Validator-Warnings"],10),
					recursion : parseInt(head.headers["X-W3C-Validator-Recursion"],10)
				}
				if (callback)
					callback(response);
				return;
			} else {
				if (error)
					error({url:url, head:head});
			}
		}
		var validUrl = "http://validator.w3.org/check?uri=" + encodeURIComponent(url);
		var headUrl = "http://json-head.appspot.com/?url=" + encodeURIComponent(validUrl) + "&callback=__validate_callbacks.fn_" + callCount

		script.setAttribute("type", "text/javascript");
		document.body.appendChild(script);
		script.src = headUrl;
	}
})();